#include <stdio.h>
#include "esp_log.h"
#include "lv_app_main.h"
#include "lvgl.h"
#include "ui.h"
#include "lvgl/examples/libs/lv_example_libs.h"
#include "pcf8563.h"
#include "axp2101.h"
#include "esp_now_hal.h"
#include "led_hal.h"
#include "max30102_app.h"
#include "esp_wifi.h"

static const char *TAG = "lv_app_main";

/* define brightness start */
static uint8_t set_brightness_last, set_brightness_last_now;
/* define brightness end */

/* define lv_timer start */
static lv_timer_t *updata_task1 = NULL;
/* define lv_timer end */

/**
 * @brief relay_event_handler
 *
 * @param e
 */
static void relay_event_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *obj = lv_event_get_target(e);
    if (code == LV_EVENT_VALUE_CHANGED)
    {
        if (obj == ui_Living_Light_Switch)
        {
            if (lv_obj_has_state(obj, LV_STATE_CHECKED) == 1)
            {
#if LV_APP_MAIN_DEBUG
                printf("ui_Living_Light_Switch:1\r\n");
#endif
                esp_now_send_data("[0]:0");
            }
            else
            {
#if LV_APP_MAIN_DEBUG
                printf("ui_Living_Light_Switch:0\r\n");
#endif
                esp_now_send_data("[0]:1");
            }
        }
        else if (obj == ui_Living_Fan_Switch)
        {
            if (lv_obj_has_state(obj, LV_STATE_CHECKED) == 1)
            {
#if LV_APP_MAIN_DEBUG
                printf("ui_Living_Fan_Switch:1\r\n");
#endif
                esp_now_send_data("[1]:0");
            }
            else
            {
#if LV_APP_MAIN_DEBUG
                printf("ui_Living_Fan_Switch:0\r\n");
#endif
                esp_now_send_data("[1]:1");
            }
        }
        else if (obj == ui_Living_Air_C_Switch)
        {
            if (lv_obj_has_state(obj, LV_STATE_CHECKED) == 1)
            {
#if LV_APP_MAIN_DEBUG
                printf("ui_Air_C_Switch:1\r\n");
#endif
                esp_now_send_data("[2]:0");
            }
            else
            {
#if LV_APP_MAIN_DEBUG
                printf("ui_Air_C_Switch:0\r\n");
#endif
                esp_now_send_data("[2]:1");
            }
        }
        else if (obj == ui_Living_Smart_TV_Switch)
        {
            if (lv_obj_has_state(obj, LV_STATE_CHECKED) == 1)
            {
#if LV_APP_MAIN_DEBUG
                printf("ui_Living_TV_Switch:1\r\n");
#endif
                esp_now_send_data("[3]:0");
            }
            else
            {
#if LV_APP_MAIN_DEBUG
                printf("ui_Living_TV_Switch:0\r\n");
#endif
                esp_now_send_data("[3]:1");
            }
        }
        else if (obj == ui_Living_Air_P_Switch)
        {
            if (lv_obj_has_state(obj, LV_STATE_CHECKED) == 1)
            {
#if LV_APP_MAIN_DEBUG
                printf("ui_Living_Air_P_Switch:1\r\n");
#endif
                esp_now_send_data("[4]:0");
            }
            else
            {
#if LV_APP_MAIN_DEBUG
                printf("ui_Living_Air_P_Switch:0\r\n");
#endif
                esp_now_send_data("[4]:1");
            }
        }
        else if (obj == ui_Bed_Light_Switch)
        {
            if (lv_obj_has_state(obj, LV_STATE_CHECKED) == 1)
            {
#if LV_APP_MAIN_DEBUG
                printf("ui_Bed_Light_Switch:1\r\n");
#endif
                esp_now_send_data("[5]:0");
            }
            else
            {
#if LV_APP_MAIN_DEBUG
                printf("ui_Bed_Light_Switch:0\r\n");
#endif
                esp_now_send_data("[5]:1");
            }
        }
        else if (obj == ui_Bed_Fan_Switch)
        {
            if (lv_obj_has_state(obj, LV_STATE_CHECKED) == 1)
            {
#if LV_APP_MAIN_DEBUG
                printf("ui_Bed_Fan_Switch:1\r\n");
#endif
                esp_now_send_data("[6]:0");
            }
            else
            {
#if LV_APP_MAIN_DEBUG
                printf("ui_Bed_Fan_Switch:0\r\n");
#endif
                esp_now_send_data("[6]:1");
            }
        }
        else if (obj == ui_Bed_Air_C_Switch)
        {
            if (lv_obj_has_state(obj, LV_STATE_CHECKED) == 1)
            {
#if LV_APP_MAIN_DEBUG
                printf("ui_Bed_A_C_Switch:1\r\n");
#endif
                esp_now_send_data("[7]:0");
            }
            else
            {
#if LV_APP_MAIN_DEBUG
                printf("ui_Bed_A_C_Switch:0\r\n");
#endif
                esp_now_send_data("[7]:1");
            }
        }
    }
}

/**
 * @brief update_switch_status
 *
 */
static void update_switch_status(void)
{
    if (esp_now_get_switch_status(LIVING_ROOM_LIGHT))
        lv_obj_clear_state(ui_Living_Light_Switch, LV_STATE_CHECKED); /* close */
    else
        lv_obj_add_state(ui_Living_Light_Switch, LV_STATE_CHECKED); /* open */

    if (esp_now_get_switch_status(LIVING_ROOM_FAN))
        lv_obj_clear_state(ui_Living_Fan_Switch, LV_STATE_CHECKED); /* close */
    else
        lv_obj_add_state(ui_Living_Fan_Switch, LV_STATE_CHECKED); /* open */

    if (esp_now_get_switch_status(LIVING_ROOM_AIR_C))
        lv_obj_clear_state(ui_Living_Air_C_Switch, LV_STATE_CHECKED); /* close */
    else
        lv_obj_add_state(ui_Living_Air_C_Switch, LV_STATE_CHECKED); /* open */

    if (esp_now_get_switch_status(LIVING_ROOM_SMART_TV))
        lv_obj_clear_state(ui_Living_Smart_TV_Switch, LV_STATE_CHECKED); /* close */
    else
        lv_obj_add_state(ui_Living_Smart_TV_Switch, LV_STATE_CHECKED); /* open */

    if (esp_now_get_switch_status(LIVING_ROOM_AIR_P))
        lv_obj_clear_state(ui_Living_Air_P_Switch, LV_STATE_CHECKED); /* close */
    else
        lv_obj_add_state(ui_Living_Air_P_Switch, LV_STATE_CHECKED); /* open */

    if (esp_now_get_switch_status(BED_ROOM_LIGHT))
        lv_obj_clear_state(ui_Bed_Light_Switch, LV_STATE_CHECKED); /* close */
    else
        lv_obj_add_state(ui_Bed_Light_Switch, LV_STATE_CHECKED); /* open */

    if (esp_now_get_switch_status(BED_ROOM_FAN))
        lv_obj_clear_state(ui_Bed_Fan_Switch, LV_STATE_CHECKED); /* close */
    else
        lv_obj_add_state(ui_Bed_Fan_Switch, LV_STATE_CHECKED); /* open */

    if (esp_now_get_switch_status(BED_ROOM_AIRC))
        lv_obj_clear_state(ui_Bed_Air_C_Switch, LV_STATE_CHECKED); /* close */
    else
        lv_obj_add_state(ui_Bed_Air_C_Switch, LV_STATE_CHECKED); /* open */
}

/**
 * @brief setting_time_event_handler
 *
 */
static void setting_time_event_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);

    if (code == LV_EVENT_CLICKED)
    {
        pcf8563_set_time(lv_roller_get_selected(ui_Time_Sec_Roller) + 1,
                         lv_roller_get_selected(ui_Time_Min_Roller) + 1,
                         lv_roller_get_selected(ui_Time_Hour_Roller) + 1,
                         lv_roller_get_selected(ui_Day_Roller) + 1,
                         0,
                         lv_roller_get_selected(ui_Mon_Roller) + 1,
                         lv_roller_get_selected(ui_Year_Roller) + 2023);
    }
}

/**
 * @brief read_max30102_event_handler
 *
 */
static void read_max30102_event_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);

    if (code == LV_EVENT_CLICKED)
    {
        max30102_app_status_set();
    }
}

/**
 * @brief off_power
 *
 */
static void off_axp2101_power_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);

    if (code == LV_EVENT_CLICKED)
    {
        axp2101_pwr_off();
    }
}

/**
 * @brief set_esp_now_channel_handler
 *
 */
static void set_esp_now_channel_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);

    if (code == LV_EVENT_CLICKED)
    {
        /* set wifi channel start */
        printf("dropdown_get_selected:%d\r\n", lv_dropdown_get_selected(ui_Channel_Dropdown));
        if (esp_wifi_stop() != ESP_OK)
        {
            printf("esp_wifi_stop fail.\r\n");
        }
        else
        {
            printf("esp_wifi_stop successfully.\r\n");
            if (esp_wifi_start() != ESP_OK)
            {
                printf("esp_wifi_start fail.\r\n");
            }
            else
            {
                printf("esp_wifi_start successfully.\r\n");
                if (esp_wifi_set_channel(lv_dropdown_get_selected(ui_Channel_Dropdown), WIFI_SECOND_CHAN_NONE) != ESP_OK)
                {
                    printf("esp_wifi_set_channel fail.\r\n");
                }
                else
                {
                    printf("esp_wifi_set_channel successfully.\r\n");
                }
            }
        }
        /* set wifi channel start */
    }
}

/**
 * @brief set_esp_now_channel_handler
 *
 */
static void set_esp_now_broadcast_addr_handler(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    uint8_t numbers[6];
    if (code == LV_EVENT_CLICKED)
    {
        /* set wifi channel start */
        printf("MAC_Addr:%s\r\n", lv_textarea_get_text(ui_MAC_TextArea));
        sscanf(lv_textarea_get_text(ui_MAC_TextArea), "%hhu.%hhu.%hhu.%hhu.%hhu.%hhu", &numbers[0], &numbers[1], &numbers[2], &numbers[3], &numbers[4], &numbers[5]);
        esp_now_set_broadcast_addr(numbers);
        /* set wifi channel start */
    }
}

/**
 * @brief updata_task1_cb
 *
 * @param tmr lvgl timer struct
 */
static void updata_task1_cb(lv_timer_t *tmr)
{
    /* update switch status start */
    if (esp_now_get_switch_status(RECV_STATUS) == ESP_OK)
    {
        esp_now_clear_rec_status();
        update_switch_status();
    }
    lv_label_set_text_fmt(ui_BroadCast_MAC_Label, "%d.%d.%d.%d.%d.%d",
                          get_espnow_broadcast_addr()[0],
                          get_espnow_broadcast_addr()[1],
                          get_espnow_broadcast_addr()[2],
                          get_espnow_broadcast_addr()[3],
                          get_espnow_broadcast_addr()[4],
                          get_espnow_broadcast_addr()[5]);
    /* update switch status end */

    /* update time tata start */
    lv_img_set_angle(ui_Clock_Sec_Page1_Image, pcf8563_get_data(SEC) * 60);
    lv_img_set_angle(ui_Clock_Min_Page1_Image, pcf8563_get_data(MIN) * 60);
    if (pcf8563_get_data(HOUR) > 12)
    {
        lv_img_set_angle(ui_Clock_Hour_Page1_Image, ((pcf8563_get_data(HOUR) - 12) * 300 + pcf8563_get_data(MIN)));
    }
    else
    {
        lv_img_set_angle(ui_Clock_Hour_Page1_Image, (pcf8563_get_data(HOUR) * 300) + pcf8563_get_data(MIN));
    }
    lv_label_set_text_fmt(ui_Clock_Time_Page2_Label, "%02d : %02d", pcf8563_get_data(HOUR), pcf8563_get_data(MIN));
    switch (pcf8563_get_data(WDAY))
    {
    case 0:
        lv_label_set_text_fmt(ui_Clock_Date_Page2_Label, "%d-%02d-%02d  Mon", pcf8563_get_data(YEAR), pcf8563_get_data(MON), pcf8563_get_data(MDAY));
        break;
    case 1:
        lv_label_set_text_fmt(ui_Clock_Date_Page2_Label, "%d-%02d-%02d  Tues", pcf8563_get_data(YEAR), pcf8563_get_data(MON), pcf8563_get_data(MDAY));
        break;
    case 2:
        lv_label_set_text_fmt(ui_Clock_Date_Page2_Label, "%d-%02d-%02d  Wed", pcf8563_get_data(YEAR), pcf8563_get_data(MON), pcf8563_get_data(MDAY));
        break;
    case 3:
        lv_label_set_text_fmt(ui_Clock_Date_Page2_Label, "%d-%02d-%02d  Thur", pcf8563_get_data(YEAR), pcf8563_get_data(MON), pcf8563_get_data(MDAY));
        break;
    case 4:
        lv_label_set_text_fmt(ui_Clock_Date_Page2_Label, "%d-%02d-%02d  Fri", pcf8563_get_data(YEAR), pcf8563_get_data(MON), pcf8563_get_data(MDAY));
        break;
    case 5:
        lv_label_set_text_fmt(ui_Clock_Date_Page2_Label, "%d-%02d-%02d  Sat", pcf8563_get_data(YEAR), pcf8563_get_data(MON), pcf8563_get_data(MDAY));
        break;
    case 6:
        lv_label_set_text_fmt(ui_Clock_Date_Page2_Label, "%d-%02d-%02d  Sun", pcf8563_get_data(YEAR), pcf8563_get_data(MON), pcf8563_get_data(MDAY));
        break;
    default:
        break;
    }
    lv_arc_set_value(ui_Hour_Arc, pcf8563_get_data(HOUR));
    lv_arc_set_value(ui_Min_Arc, pcf8563_get_data(MIN));
    lv_arc_set_value(ui_Sec_Arc, pcf8563_get_data(SEC));
    /* update time tata end */

    /* update max30102 data start */
    lv_label_set_text_fmt(ui_Spo2_Label, "SpO2 : %d %%", max30102_get_spo2());
    lv_label_set_text_fmt(ui_Heart_Rate_Label, "Rate : %d p/m", max30102_get_heart_rate());
    lv_arc_set_value(ui_Heart_Arc, max30102_get_heart_rate());
    lv_label_set_text_fmt(ui_Heart_Label, "%d", max30102_get_heart_rate());
    /* update max30102 data start */

    /* update vbat level start */
    lv_label_set_text_fmt(ui_Vbat_Level_Label, "%d%%", axp2101_bat_level());
    lv_arc_set_value(ui_Vbat_Arc, axp2101_bat_level());
    lv_slider_set_value(ui_Vbat_Slider, axp2101_bat_level(), LV_ANIM_OFF);
    if (axp2101_is_charging())
    {
        lv_obj_set_style_bg_color(ui_Vbat_Slider, lv_color_hex(0x66FFCC), LV_PART_INDICATOR | LV_STATE_DEFAULT);
    }
    else
    {
        lv_obj_set_style_bg_color(ui_Vbat_Slider, lv_color_hex(0xD1D1D1), LV_PART_INDICATOR | LV_STATE_DEFAULT);
    }
    /* update vbat level end */

    /* update wifi channel start */
    lv_label_set_text_fmt(ui_Bind_Label1, "  CHANNEL : %d  ", esp_now_get_channel());
    lv_label_set_text_fmt(ui_Channel_Label, "%d", esp_now_get_channel());
    /* update wifi channel end */

    /* update max30102 state start */
    if (max30102_app_status_get())
    {
        lv_obj_clear_flag(ui_Spinner1, LV_OBJ_FLAG_HIDDEN);
    }
    else
    {
        lv_obj_add_flag(ui_Spinner1, LV_OBJ_FLAG_HIDDEN);
    }
    /* update max30102 state end */

    set_brightness_last_now = lv_slider_get_value(ui_Setting_BLK_Slider);
    if (set_brightness_last_now != set_brightness_last)
    {
        set_brightness_last = set_brightness_last_now;
        ESP_LOGI(TAG, "brightness:%d %%", set_brightness_last_now);
        ledc_set_brightness(lv_slider_get_value(ui_Setting_BLK_Slider));
    }
}

/**
 * @brief lv_add_timer
 *
 */
void lv_add_timer(void)
{
    /* add lv_timer start */
    updata_task1 = lv_timer_create(updata_task1_cb, 250, 0); /* T = 250ms */
    /* add lv_timer end */
}

/**
 * @brief lv_app_create_cb
 *
 */
void lv_app_create_cb(void)
{
    /* create language switch cb event start */

    /* create language switch cb event start */

    /* init switch button obj state start */

    /* init switch button obj state end */

    /* create relay switch cb event start */
    lv_obj_add_event_cb(ui_Living_Light_Switch, relay_event_handler, LV_EVENT_ALL, NULL);    /* bit0 */
    lv_obj_add_event_cb(ui_Living_Fan_Switch, relay_event_handler, LV_EVENT_ALL, NULL);      /* bit1 */
    lv_obj_add_event_cb(ui_Living_Air_C_Switch, relay_event_handler, LV_EVENT_ALL, NULL);    /* bit2 */
    lv_obj_add_event_cb(ui_Living_Smart_TV_Switch, relay_event_handler, LV_EVENT_ALL, NULL); /* bit3 */
    lv_obj_add_event_cb(ui_Living_Air_P_Switch, relay_event_handler, LV_EVENT_ALL, NULL);    /* bit4 */
    lv_obj_add_event_cb(ui_Bed_Light_Switch, relay_event_handler, LV_EVENT_ALL, NULL);       /* bit5 */
    lv_obj_add_event_cb(ui_Bed_Fan_Switch, relay_event_handler, LV_EVENT_ALL, NULL);         /* bit6 */
    lv_obj_add_event_cb(ui_Bed_Air_C_Switch, relay_event_handler, LV_EVENT_ALL, NULL);
    /* create relay switch cb event start */

    /* create set time button cb start */
    lv_obj_add_event_cb(ui_Setting_Time_Button, setting_time_event_handler, LV_EVENT_ALL, NULL);
    /* create set time button cb end */

    /* create read max30102 button cb start */
    lv_obj_add_event_cb(ui_Body_Button, read_max30102_event_handler, LV_EVENT_ALL, NULL);
    /* create read max30102 button cb end */

    /* create off axp2101 button cb start */
    lv_obj_add_event_cb(ui_PWR_Button, off_axp2101_power_handler, LV_EVENT_ALL, NULL);
    /* create off axp2101 button cb end */

    /* create set_esp_now_channel and broadcast mac button cb start */
    lv_obj_add_event_cb(ui_Bind_Button, set_esp_now_channel_handler, LV_EVENT_ALL, NULL);
    lv_obj_add_event_cb(ui_MAC_Button, set_esp_now_broadcast_addr_handler, LV_EVENT_ALL, NULL);
    /* create set_esp_now_channel and broadcast mac button cb end */
}
